#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
启动脚本
用于启动瀚越包装方案匹配工具
"""

import os
import sys
import subprocess
import venv

# 获取脚本所在目录的父目录作为项目根目录
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__)))
VENV_DIR = os.path.join(PROJECT_ROOT, "venv")


def check_python_version():
    """检查Python版本"""
    required_version = (3, 8)
    current_version = sys.version_info
    
    if current_version < required_version:
        print(f"错误: 需要Python {required_version[0]}.{required_version[1]} 或更高版本，当前版本是 {current_version[0]}.{current_version[1]}.{current_version[2]}")
        return False
    return True


def create_virtual_environment():
    """创建虚拟环境"""
    print(f"正在创建虚拟环境，路径: {VENV_DIR}")
    try:
        venv.create(VENV_DIR, with_pip=True)
        print("虚拟环境创建成功")
        return True
    except Exception as e:
        print(f"创建虚拟环境失败: {str(e)}")
        return False


def get_venv_python():
    """获取虚拟环境中的Python解释器路径"""
    if sys.platform.startswith("win"):
        return os.path.join(VENV_DIR, "Scripts", "python.exe")
    else:
        return os.path.join(VENV_DIR, "bin", "python")


def install_dependencies(use_venv=True):
    """安装项目依赖"""
    print("正在检查并安装项目依赖...")
    requirements_file = os.path.join(PROJECT_ROOT, "requirements.txt")
    
    try:
        # 确定使用哪个Python解释器
        if use_venv and os.path.exists(VENV_DIR):
            python_exe = get_venv_python()
        else:
            python_exe = sys.executable
        
        # 使用pip安装依赖，添加国内镜像源加速下载
        cmd = [
            python_exe, 
            "-m", "pip", 
            "install", 
            "-r", requirements_file,
            "-i", "https://pypi.tuna.tsinghua.edu.cn/simple"
        ]
        subprocess.check_call(cmd)
        print("依赖安装成功")
        return True
    except Exception as e:
        print(f"安装依赖失败: {str(e)}")
        return False


def run_in_venv():
    """在虚拟环境中运行应用"""
    # 获取虚拟环境中的Python解释器
    venv_python = get_venv_python()
    
    # 构建命令行参数，排除当前脚本名
    args = sys.argv[1:]
    cmd = [venv_python, os.path.abspath(__file__)] + args
    
    # 在虚拟环境中重新运行脚本
    try:
        subprocess.check_call(cmd)
        return True
    except Exception as e:
        print(f"在虚拟环境中运行应用失败: {str(e)}")
        return False


def main():
    """主函数"""
    # 检查Python版本
    if not check_python_version():
        sys.exit(1)
    
    # 检查是否已经在虚拟环境中运行
    in_venv = hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix
    
    # 如果不在虚拟环境中且虚拟环境不存在，则创建虚拟环境
    if not in_venv:
        if not os.path.exists(VENV_DIR):
            if not create_virtual_environment():
                print("警告: 创建虚拟环境失败，将尝试在当前环境中安装依赖")
                # 尝试在当前环境中安装依赖
                if not install_dependencies(use_venv=False):
                    sys.exit(1)
            else:
                # 创建成功后，在虚拟环境中重新运行
                sys.exit(0 if run_in_venv() else 1)
        else:
            # 虚拟环境存在但未激活，重新在虚拟环境中运行
            sys.exit(0 if run_in_venv() else 1)
    
    # 已经在虚拟环境中运行，安装依赖
    if not install_dependencies():
        print("警告: 依赖安装失败，将尝试直接运行")
    
    # 添加src目录到Python路径
    src_dir = os.path.join(PROJECT_ROOT, "src")
    if src_dir not in sys.path:
        sys.path.insert(0, src_dir)
    
    # 启动应用程序
    try:
        from app.main import main as app_main
        print("正在启动瀚越包装方案匹配工具...")
        app_main()
    except ImportError as e:
        print(f"导入模块失败: {str(e)}")
        print("请确保所有依赖已正确安装")
        sys.exit(1)
    except Exception as e:
        print(f"启动应用程序失败: {str(e)}")
        sys.exit(1)


if __name__ == "__main__":
    main()